package com.bob.light.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.bob.light.R
import com.bob.light.TuyaHomeSDKHelper
import com.bob.light.activity.delegate.FamilyManagerDelegate
import com.bob.light.isVisibilityOrGone
import com.bob.light.setOnSingleClickListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.bob.light.dialog.MessageDialog
import com.tuya.smart.home.sdk.bean.HomeBean
import kotlinx.android.synthetic.main.app_activity_family_manager.*
import kotlinx.android.synthetic.main.app_title_bar.*
import java.lang.StringBuilder

class FamilyManagerActivity : AppCompatActivity() {

    private val mFamilyManagerDelegate: FamilyManagerDelegate? = FamilyManagerDelegate()
    private var mAdapter: BaseQuickAdapter<HomeBean, BaseViewHolder>? = null
    private var mFamilyName = "我的家"
    private var mRoomList = arrayListOf("我家的客厅", "我家的主卧", "我家的次卧", "我家的餐厅", "我家的厨房", "我家的书房")

    companion object {

        @JvmStatic
        fun navigation(activity: AppCompatActivity?) {
            activity?.let { context ->
                val intent = Intent(context, FamilyManagerActivity::class.java)
                intent.putExtra(FLAG, 0)
                context.startActivity(intent)
            }
        }

        @JvmStatic
        fun navigationForResult(activity: AppCompatActivity?) {
            activity?.let { context ->
                val intent = Intent(context, FamilyManagerActivity::class.java)
                intent.putExtra(FLAG, 1)
                context.startActivityForResult(intent, REQUEST_CODE)
            }
        }

        const val REQUEST_CODE = 0x0000f011
        private const val FLAG = "FLAG"
        const val HOME_ID = "homeId"
        const val HOME_NAME = "homeName"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.app_activity_family_manager)
        mFamilyManagerDelegate?.let {
            lifecycle.addObserver(it)
        }
        initView()
        initData()
    }

    private fun initView() {
        fl_back_pressed?.setOnSingleClickListener {
            finish()
        }
        tv_title_name?.text = title
        tv_create_family?.setOnSingleClickListener {
            TuyaHomeSDKHelper.createFamily(mFamilyName, mRoomList) { homeBean ->
                homeBean?.let {
                    mAdapter?.addData(0, it)
                    recycle_item_family?.smoothScrollToPosition(0)
                }
            }
        }
        recycle_item_family?.let { recyclerView ->
            recyclerView.layoutManager = LinearLayoutManager(this@FamilyManagerActivity)
            mAdapter = initAdapter()
            mAdapter?.setOnItemLongClickListener { adapter, _, position ->
                showDeleteFamilyDialog(adapter.data[position] as HomeBean, position)
                true
            }
            mAdapter?.setOnItemClickListener { adapter, _, position ->
                if (((intent?.getIntExtra(FLAG, 0))?:0) == 1) {
                    val data = adapter.data[position]
                    if (data is HomeBean) {
                        val intent = Intent()
                        intent.putExtra(HOME_NAME, data.name)
                        intent.putExtra(HOME_ID, data.homeId)
                        setResult(1, intent)
                        finish()
                    }
                }
            }
            recyclerView.adapter = mAdapter
        }
    }

    private fun initData() {
        TuyaHomeSDKHelper.queryFamilyList { homeList ->
            mAdapter?.setNewData(homeList)
            homeList?.forEachIndexed { index, homeBean ->
                TuyaHomeSDKHelper.queryFamilyDetail(homeBean.homeId) { detailBean ->
                    mAdapter?.data?.let { data ->
                        if (detailBean != null) {
                            data[index].rooms.addAll(detailBean.rooms)
                        }
                    }
                    mAdapter?.notifyItemChanged(index)
                }
            }
        }
    }

    private fun initAdapter(): BaseQuickAdapter<HomeBean, BaseViewHolder> {
        return object : BaseQuickAdapter<HomeBean, BaseViewHolder>(R.layout.app_item_family) {
            override fun convert(helper: BaseViewHolder?, item: HomeBean?) {
                if (item == null) {
                    return
                }
                helper?.getView<View>(R.id.view_line)?.isVisibilityOrGone(
                    data.size > 0 && helper.adapterPosition != (data.size - 1))
                val text= "${item.name}-ID=${item.homeId}"
                helper?.getView<TextView>(R.id.tv_family_name)?.text = text

                showRoomList(item, helper)
            }

            private fun showRoomList(item: HomeBean, helper: BaseViewHolder?) {
                if (item.rooms == null || item.rooms.size <= 0) {
                    helper?.getView<TextView>(R.id.tv_rooms_name)?.text = ". . . . . ."
                } else {
                    val rooms = StringBuilder()
                    item.rooms?.forEachIndexed { index, roomBean ->
                        rooms.append(roomBean.name).append("-ID=").append(roomBean.roomId)
                        if (index < (item.rooms.size - 1)) {
                            rooms.append("\n")
                        }
                    }
                    helper?.getView<TextView>(R.id.tv_rooms_name)?.text = rooms.toString()
                }
            }
        }
    }

    private fun showDeleteFamilyDialog(item: HomeBean, position: Int) {
        MessageDialog(this@FamilyManagerActivity)
            .content("删除 ${item.name}")
            .setOnConfirmClickListener {
                deleteFamily(item, position)
            }
            .show()
    }

    private fun deleteFamily(item: HomeBean, position: Int) {
        TuyaHomeSDKHelper.removeFamily(item.homeId) {
            mAdapter?.data?.remove(item)
            if (position > 0) {
                mAdapter?.notifyItemRemoved(position)
                mAdapter?.notifyItemChanged(position - 1, 500L)
            } else {
                mAdapter?.notifyDataSetChanged()
            }
        }
    }

    override fun finish() {
        if (((intent?.getIntExtra(FLAG, 0))?:0) != 1) {
            MainActivity.navigation(this@FamilyManagerActivity)
        }
        super.finish()
    }

    override fun onDestroy() {
        super.onDestroy()
        mFamilyManagerDelegate?.let {
            lifecycle.removeObserver(it)
        }
    }

}